package com.bhkj.pdjhbgnewproject.core.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;

import com.bhkj.pdjhbgnewproject.common.bean.PersonInfoBean;
import com.bhkj.pdjhbgnewproject.common.contanct.Contacts;
import com.bhkj.pdjhbgnewproject.core.main.MainActivity;
import com.bhkj.pdjhbgnewproject.core.register.RegesterServer;
import com.bhkj.pdjhbgnewproject.core.viewmodel.MainViewRealModel;
import com.bhkj.pdjhbgnewproject.core.viewmodel.WindowStatusModel;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("rawtypes")
public class ObtainPdInfoService extends Service {
    private PdInfoSchduledExcutor pdInfoSchduledExcutor;
    private ScheduledExecutorService scheduledThreadPool;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        super.onCreate();
        //新增---------------------------------------------
        String CHANNEL_ONE_ID = "com.bhkj.pdjhbgnewproject";
        String CHANNEL_ONE_NAME = "Channel One";
        NotificationChannel notificationChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                    CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setShowBadge(true);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(notificationChannel);
        }
        new WsDataManager();
        updateUI();

    }

    private void updateUI() {
        MainActivity topActivity = (MainActivity) ActivityUtils.getTopActivity();
        if (topActivity != null) {
            MainViewRealModel mainViewRealModel = ViewModelProviders.of(topActivity).get(MainViewRealModel.class);
            mainViewRealModel.getPersonInfoLiveData().observe(topActivity, new Observer<PersonInfoBean>() {
                @Override
                public void onChanged(@Nullable PersonInfoBean personInfoBean) {
                    LogUtils.d("信息：" + personInfoBean.getCode());
                    obtainPdInfoFromNet(personInfoBean);
                }
            });

            WindowStatusModel windowStatusModel = ViewModelProviders.of(topActivity).get(WindowStatusModel.class);
            windowStatusModel.getWindowStatusLiveData().observe(topActivity, new Observer<String>() {
                @Override
                public void onChanged(@Nullable String s) {
                    switch (Objects.requireNonNull(s)) {
                        case Contacts.PUSH_LOGOUT:

                            cancelTask();
                            break;

                        case Contacts.PUSH_RESUME_SERVICE:
                            break;
                        case Contacts.PUSH_END_SERVICE:
                            break;
                        default:
                            break;
                    }
                }
            });
        }
    }


    /**
     * 取消获取排队信息任务
     * shutdown 不再接收新的任务，等待所有的任务执行完毕，然后关闭线程池
     * awaitTermination 监测线程池的状态，等待1s的时候，获取一下线程池是否关闭，如果关闭返回true；如果没有关闭返回
     * false，调用ShutDownNow产生中断异常
     */
    private void cancelTask() {
        if (scheduledThreadPool != null) {
            try {
                scheduledThreadPool.shutdown();
                if (!scheduledThreadPool.awaitTermination(1, TimeUnit.SECONDS)) {
                    scheduledThreadPool.shutdownNow();
                }
                scheduledThreadPool = null;
            } catch (InterruptedException e) {
                scheduledThreadPool.shutdownNow();
                Thread.currentThread().interrupt();//保持中断
                scheduledThreadPool = null;
                e.printStackTrace();
            }
        }
    }


    private void obtainPdInfoFromNet(PersonInfoBean personInfoBean) {
        if (pdInfoSchduledExcutor == null) {
            pdInfoSchduledExcutor = new PdInfoSchduledExcutor(personInfoBean);
        }

        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();

        if (scheduledThreadPool == null) {
            scheduledThreadPool = new ScheduledThreadPoolExecutor(10, namedThreadFactory);
        }
        scheduledThreadPool.scheduleWithFixedDelay(pdInfoSchduledExcutor, 0, 1, TimeUnit.SECONDS);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
